package com.demo.jingxi.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.jingxi.dao.RoleMapper;
import com.demo.jingxi.dao.XRoleMenuMapper;
import com.demo.jingxi.pojo.Role;
import com.demo.jingxi.pojo.XRoleMenu;
import com.demo.jingxi.pojo.XUserRole;
import com.demo.jingxi.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
   @Autowired
    private XRoleMenuMapper roleMenuMapper;
    @Transactional
    @Override
    public void addRole(Role role) {
        this.save(role);

        for (Integer menuId : role.getMenuIdList()){
            roleMenuMapper.insert(new XRoleMenu(null,role.getId(),menuId));
        }
    }

    @Override
    public Role getRoleById(Integer id) {
        Role role = this.getById(id);
        List<Integer>  menuIdList= roleMenuMapper.getMenuIdListByRoleId(id);

        role.setMenuIdList(menuIdList);
          return role;
    }
    @Transactional
    @Override
    public void updateRole(Role role) {
        // 更新role表
        this.updateById(role);
        // 清除原有权限
        LambdaQueryWrapper<XRoleMenu> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(XRoleMenu::getRoleId,role.getId());
        roleMenuMapper.delete(wrapper);
        //新增权限
        for (Integer menuId : role.getMenuIdList()) {
            roleMenuMapper.insert(new XRoleMenu(null,role.getId(),menuId));
        }
    }

    @Override
    public void deleteRoleById(Integer id) {
        this.removeById(id);
        LambdaQueryWrapper<XRoleMenu> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(XRoleMenu::getRoleId,id);
        roleMenuMapper.delete(queryWrapper);
    }


}
